import type { NvCrudEmits, NvCrudProps } from './types'
import type { Constructor } from '@/types'
import { computed } from 'vue'
import { DefaultLayout, SimpleLayout } from './layouts'

export function useLayout(props: NvCrudProps, emits: NvCrudEmits, slots: Record<string, any>) {
  let LayoutComponet: Constructor
  const layout = props.option.layout
  if (!layout || layout === 'default') {
    LayoutComponet = DefaultLayout
  }
  else if (layout === 'simple') {
    LayoutComponet = SimpleLayout
  }
  else {
    LayoutComponet = layout
  }

  function layoutEventHandler(eventName: string, ...args: any[]) {
    emits(eventName, ...args)
  }

  const layoutSlots: Record<string, any> = {}
  const BASIC_SLOTS = ['search', 'actionbar', 'toolbar', 'multi-select-bar', 'table']
  for (const key in slots) {
    if (!BASIC_SLOTS.includes(key))
      layoutSlots[key] = slots[key]
  }

  const searchVisible = computed(() => {
    if (props.option.searchForm === false) {
      return false
    }
    return !!Object.values(props.option.fields)
      .filter(option => option.search)
      .length
  })

  return {
    LayoutComponet,
    layoutEventHandler,
    layoutSlots,
    searchVisible,
  }
}
